﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraReports.UI;

namespace WmsApp.Report
{
    public class ReportFactory
    {
        public static DataSet GetDataSet(string reportID,List<WmsService.ReportParameter> list)
        {
            try
            {
                DataSet dataSet = Factory.WmsServiceFactory.GetServiceClient().GetDataSet(reportID, list);
                return dataSet;
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ShowException(ex);
            }
            return null;
        }

        private static XtraReport GetXtraReport(string reportID)
        {
            string path = Application.StartupPath + "\\";
            if(File.Exists(path+ reportID + ".repx" ))
            {
                return XtraReport.FromFile(path + reportID + ".repx", true);
            }
            else  if(File.Exists(path + "ReportFile\\" + reportID + ".repx" ))
            {
                return XtraReport.FromFile(path + "ReportFile\\" + reportID + ".repx", true);
            }
            throw new Exception("不存在报表文件：" + reportID + ".repx");
        }

        public static void ShowReport(string reportID,List<WmsService.ReportParameter> list)
        {
            try
            {
                DataSet dataSet = Factory.WmsServiceFactory.GetServiceClient().GetDataSet(reportID, list);
                foreach (var rp in list)
                {
                    if (dataSet.Tables[rp.DbTableName].Rows.Count == 0)
                    {
                        Exceptions.ExceptionHandler.ShowException(String.Format("数据表行数为0，表名：{0}，条件：{1}", rp.DbTableName, rp.Condition));
                        return;
                    }
                }
                XtraReport report = GetXtraReport(reportID);
                report.DataSource = dataSet;
                report.ShowPreviewDialog();
            }
            catch (Exception ex)
            {
                Exceptions.ExceptionHandler.ShowException(ex);
            }
        }

        public static void WriteXmlSchema(string reportID)
        {
            DataSet dataSet = Factory.WmsServiceFactory.GetServiceClient().GetDataSet(reportID, new List<WmsService.ReportParameter>());
            dataSet.WriteXmlSchema(Application.StartupPath + "\\"+ reportID+".xml");
        }
    }
}
